package com.qianniu.napi.admin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.mapper.OrderMapper;
import com.qianniu.napi.admin.service.IResourceService;
import com.qianniu.napi.admin.service.impl.ResourceServiceImpl;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class ResourceTask {

    private static final Logger logger = LoggerFactory.getLogger(ResourceTask.class);

    @Autowired
    private IResourceService resourceService;

    //每小时实行一次，检查素材图片，重新上传到微信服务器
    @Scheduled(cron = "0 10 0/1 * * ?")
    public void checkMediaExpire() {
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>checkMediaExpire start");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        long ts = DateUtil.addDay(new Date(), 3).getTime() - 30 * 60 * 1000;//

        String tstr = String.valueOf(ts).substring(0, 10);
        long shortts = new Date().getTime();

        while (flag) {
            Wrapper<Resource> wrapper = new EntityWrapper<Resource>().eq("ismedia", 1)
                    .isNotNull("mediaid").le("createdat", shortts);

            Page page = new Page(index, limit);
            Page<Resource> list = resourceService.selectPage(page, wrapper);
            try {

                for (Resource item : list.getRecords()) {
                    logger.info("------------------------------for each start");
                    String pic = item.getPic();

                    String path = pic.indexOf("//imgcdn.") > 0 ? pic.replace(Constants.IMG_UPLOAD_CDN_HOST, "/fafa/www/images/0cdn/") :
                            pic.replace(Constants.IMG_UPLOAD_HOST, "/fafa/www/images/");

                    JSONObject jo = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_MATERIAL_IMAGE, path, 72, item.getMpid());

                    if (jo.containsKey("media_id")) {
                        Resource nresource = new Resource();
                        nresource.setId(item.getId());
                        nresource.setMediaid(jo.getString("media_id"));
                        nresource.setCreatedat(jo.getLong("created_at"));
                        nresource.setModifytime(new Date());
                        nresource.updateById();
                    }
                }
            } catch (Exception e) {
                logger.error("-------------checkStoreStat", e);
            }

            flag = list.getRecords() != null && list.getRecords().size() == limit;
            index++;
        }

        logger.debug(">>>refreshStock exe success");
    }
}
